<template>
  <div class="model-box">
    <div class="button-box">
      <div style="display: flex;">
        <ac-input v-model="filterName" style="width: 150px" placeholder="流程名称" />
        <el-button style="margin-left: 10px;" type="primary" @click="loadData">
          <cc-icon iconId="018dc9c3efe489a7d117" style="margin-right: 5px" />查询
        </el-button>
        <div @click="selectMode = !selectMode" style="margin-left: 20px;cursor: pointer">
          <el-checkbox v-model="selectMode" />
          <span style="margin-left: 5px">选择模式</span>
        </div>
        <el-button v-if="selectMode" style="margin-left: 10px;" type="primary" @click="selectAll">
          <cc-icon iconId="018dca412c4e207388f7" style="margin-right: 5px" />全选
        </el-button>
        <el-button v-if="selectMode" style="margin-left: 10px;" type="primary" @click="unselectAll">
          <cc-icon iconId="018dca412c4ebd53fd1d" style="margin-right: 5px" />取消选择
        </el-button>
      </div>
      <div class="button-item">
        <el-upload
          action=""
          :http-request="handleImport"
          :show-file-list="false"
          accept=".dat"
        >
          <el-button
            style="
              color: #ffffff;
              background-color: #00CED1;
              border: 1px solid #00CED1;
            "
          >
            <ac-icon
              iconId="018dcc257a83b0d6deab"
              title="导入流程"
              style="margin-right: 8px"
            />导入流程
          </el-button>
        </el-upload>

        <el-button
          style="
            color: #ffffff;
            background-color: #FF8C00;
            border: 1px solid #FF8C00
          "
          @click="download()"
        >
          <ac-icon
            iconId="018dcc257a840e260284"
            title="导出流程"
            style="margin-right: 8px"
          />导出流程
        </el-button>
      </div>
    </div>

    <div class="item-box" @click="addItem">
      <div style="font-size: 14px; display: flex;align-items: center">
        <ac-icon
          iconId="018dca3b4707c4c43a2f"
          size="18"
          color="#474747"
        />
        <span style="margin-left: 10px">添加流程</span>
      </div>
    </div>

    <div
      v-for="item in dataList"
      :key="item.id"
      :class="['item-box', selectMode && item.checked ? 'active' : '']"
      @click="clickItem(item)"
    >
      <div class="item-main">
        <div class="item-header">
          <div class="item-name-line">
            <div>
              <ac-icon
                v-if="item.iconId"
                :iconId="item.iconId"
                :size="25"
                style="margin-right: 10px"
              />
            </div>
            <span class="item-name" :title="item.name">{{item.name}}</span>
            <span>
              <el-tooltip
                effect="light"
                content="编辑"
                popper-class="padding-10-15"
              >
              <ac-icon
                size="15"
                iconId="018ece4f6918a49a759b"
                @click.stop="editItem(item)"
              />
            </el-tooltip>
            </span>
          </div>
        </div>
        <div class="item-remark">
          <span :title="item.description">{{item.description || '暂无描述'}}</span>
        </div>
        <div class="item-button">
          <div class="time-box"></div>
          <div class="button-list">
            <el-tooltip
              effect="light"
              content="设计"
              popper-class="padding-10-15"
            >
              <ac-icon
                size="15"
                iconId="018dca6db20c6a3aaf68"
                color="#0085f6"
                @click.stop="designItem(item)"
              />
            </el-tooltip>
            <el-tooltip
              effect="light"
              content="删除"
              popper-class="padding-10-15"
            >
              <ac-icon
                size="15"
                iconId="018dc9c3efd3a0502886"
                color="#F56C6C"
                @click.stop="deleteItem(item)"
              />
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>
  </div>

  <el-dialog
    v-model="visible"
    :title="title"
    width="600px"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="dataForm"
      label-width="100px"
      label-position="right"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="流程名称" prop="name">
            <el-input v-model="formData.name" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="流程描述" prop="description">
            <el-input v-model="formData.description" type="textarea" :rows="5"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="visible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="loading"
        @click="submit"
      >提交</el-button>
    </template>
  </el-dialog>

  <!--页面设计-->
  <el-dialog
    v-model="editorVisible"
    class="no-padding no-header no-scroll"
    :show-header="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    fullscreen
    draggable
  >
    <FlowEdit v-bind="editorOptions" @quit="editorVisible = false" />
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import api from "@/http/api";
import { ElMessage, ElMessageBox } from "element-plus";
import tool from "@/utils/tool";
import FlowEdit from "@/admin/ai/flowEdit.vue";

const selectMode = ref(false);
const filterName = ref('');
const filterSupplierId = ref('');
const dataList = ref([]);
const visible = ref(false);
const title = ref('');
const dataForm = ref();
const formData = ref({});
const paramList = ref([]);
const loading = ref(false);
const rules = ref({
  name: [
    {required: true, message: '流程名称不能为空！', trigger: 'blur'},
    {max: 100, message: '流程名称长度最多只能是100个字符', trigger: ['blur', 'change']}
  ],
  description: [
    {max: 1000, message: '流程描述长度最多只能是1000个字符', trigger: ['blur', 'change']}
  ]
});

const editorVisible = ref(false);
const editorOptions = ref({id: ''});

const addItem = () => {
  formData.value = { paramList: {} };
  paramList.value = [];
  title.value = "新增流程";
  loading.value = false;
  visible.value = true;
};

const clickItem = item => {
  if (selectMode.value) {
    item.checked = !item.checked;
  } else {
    designItem(item);
  }
};

const editItem = async(item) => {
  if (!item) return;
  formData.value = tool.deepClone(item);
  if (formData.value.paramJson) {
    formData.value.paramList = JSON.parse(formData.value.paramJson);
  } else {
    formData.value.paramList = {};
  }
  title.value = "编辑流程";
  loading.value = false;
  visible.value = true;
};

const designItem = (item) => {
  editorOptions.value.id = item.id;
  editorVisible.value = true;
};

const submit = () => {
  dataForm.value.validate(valid => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        loading.value = true;
        const data = tool.deepClone(formData.value);
        if (data.paramList && Object.keys(data.paramList).length > 0) {
          data.paramJson = JSON.stringify(data.paramList);
        } else {
          data.paramJson = '';
        }
        delete data.paramList;
        api.post('/system/aiFlow/save', data).then(res => {
          if(res.code === '1') {
            visible.value = false;
            ElMessage.success(res.message);
            loadData();
          } else {
            ElMessage.error(res.message);
          }
          loading.value = false;
        }).catch(() => {
          loading.value = false;
        });
      });
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  });
};

const download = () => {
  const ids = dataList.value.filter(item => item.checked).map(item => item.id);
  if (!ids || ids.length === 0) {
    ElMessage.error("请先选择要导出的流程！");
    return;
  }

  api.downloadFile('/system/aiFlow/exportData', {ids: ids}).then(res => api.saveFileLocal(res));
};

const deleteItem = (supplierModel) => {
  ElMessageBox.confirm('请确认是否删除流程【' + supplierModel.name + '】？', '提示', {type: 'warning'}).then(() => {
    api.post('/system/aiFlow/delete', supplierModel).then(res => {
      if(res.code === '1') {
        ElMessage.success(res.message);
        loadData();
      } else {
        ElMessage.error(res.message);
      }
    });
  });
};

const handleImport = (file) => {
  api.uploadFile('/system/aiFlow/importData', {'file': file.file}).then((res) => {
    ElMessage.success(res.message);
    loadData();
  });
};

const loadData = () => {
  dataList.value = [];
  api.post('/system/aiFlow/queryList', {name: filterName.value, supplierId: filterSupplierId.value}).then(res => {
    dataList.value = res.data || [];
  });
};

const selectAll = () => {
  dataList.value.forEach(data => data.checked = true);
};

const unselectAll = () => {
  dataList.value.forEach(data => data.checked = false);
};

onMounted(() => {
  loadData();
});
</script>

<style scoped lang="scss">
.model-box {
  padding: 20px;
  height: calc(100% - 40px);
  background: #f5f5f5;
  display: grid;
  grid-template-columns: repeat(auto-fill, 250px);
  grid-gap: 15px;
  justify-content: center;
  align-content: flex-start;
  overflow: auto;
  .button-box {
    display: flex;
    width: 100%;
    grid-column: 1 / -1;
    text-align: right;
    .button-item {
      flex-grow: 1;
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      gap: 15px;
      margin-bottom: 20px;
    }
  }
  .item-box {
    cursor: pointer;
    border: 1px solid transparent;
    width: 250px;
    min-height: 140px;
    background: #ffffff;
    border-radius: 10px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-content: center;
    .item-main {
      width: 100%;
      padding: 15px 20px;
      display: flex;
      flex-direction: column;
      .item-header {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        .item-name-line {
          width: 1px;
          flex-grow: 1;
          box-sizing: border-box;
          display: flex;
          flex-direction: row;
          align-items: center;
          .item-name {
            width: 1px;
            flex-grow: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            box-sizing: border-box;
            color: #333333;
            font-weight: bold;
            font-size: 16px;
          }
        }

        .ac-icon {
          flex-shrink: 0;
          cursor: pointer;
        }

        .el-checkbox__label {
          padding-left: 0;
        }
      }

      .item-remark {
        flex-grow: 1;
        margin-top: 8px;
        color: #888888;
        font-size: 12px;
        > span {
          width: 100%;
          display: block;
          line-height: 1.2;
          overflow: hidden;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }
      }
      .item-button {
        display: flex;
        flex-direction: row;
        align-items: center;
        .time-box {
          flex-grow: 1;
          color: #999;
        }

        .ac-icon {
          cursor: pointer;
          margin-left: 12px;
        }
      }
    }
  }

  .item-box:hover {
    box-shadow: 0 0 20px 0 rgba(64, 158, 255, 0.25);
  }

  .item-box.active {
    border: 1px solid rgb(64, 158, 255);
    box-shadow: inset 0 0 0 1px rgb(64, 158, 255);
  }
}
.param-box {
  flex-grow: 1;
}
.param-item {
  width: 100%;
  display: flex;
  flex-direction: row;
  .param-name, .param-key {
    width: 120px;
    flex-shrink: 0;
    margin-right: 8px;
  }
  .param-description {
    flex-grow: 1;
    margin-right: 8px;
  }
  .param-delete {
    cursor: pointer;
    display: flex;
  }
}
.predefine {
  display: flex;
  > div {
    cursor: pointer;
    display: inline;
    line-height: 1.2;
    margin-right: 8px;
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 5px 12px;
  }
}
</style>